package com.parktech.sun.web.controller.management.industryservice;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.industryservice.IndustryService;
import com.parktech.sun.domain.model.industryservice.IndustryServiceInfoCategory;
import com.parktech.sun.domain.model.industryservice.IndustryServiceInformation;
import com.parktech.sun.domain.model.industryservice.IndustryServiceInformationAttachment;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.industryservice.IndustryServiceService;
import com.parktech.sun.utils.FileHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-12
 * Time: 下午10:52
 */
@Controller
@RequestMapping("/management/industryservice/informations")
public class IndustryServiceInformationController {
    
    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private IndustryServiceService industryServiceService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public IndustryServiceInformationController(IndustryServiceService industryServiceService) {
        this.industryServiceService = industryServiceService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute IndustryServiceSearchForm industryServiceInformationSearchForm) {

        Page page = new Page(pageSize, industryServiceInformationSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/industryservice/industryServiceInformationSearch");

        return modelAndView.addObject(
                industryServiceService.searchInformation(
                        industryServiceInformationSearchForm.getTitle(),
                        industryServiceInformationSearchForm.getCategory(),
                        industryServiceInformationSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("industryServiceInformationIds") Long[] industryServiceInformationIds) {
        industryServiceService.deleteAll(IndustryServiceInformation.class, industryServiceInformationIds);
        return "redirect:search";
    }

    @ModelAttribute("allCategories")
    public List<IndustryService> populateAllCategories() {
        return industryServiceService.search(null, new Page(1000, 1)).getResult();
    }

    @ModelAttribute("allSubCategories")
    public Map<Long, List<IndustryServiceInfoCategory>> populateAllSubCategories() {
        Map<Long, List<IndustryServiceInfoCategory>> ret = new TreeMap<Long, List<IndustryServiceInfoCategory>>();
        List<IndustryService> serviceList = populateAllCategories();
        for (IndustryService industryService : serviceList) {
            ret.put(industryService.getId(), industryServiceService.searchCategory(null, industryService.getId(), new Page(1000, 1)).getResult());
        }
        return ret;
    }

    @ModelAttribute("allPositions")
    public Map<Integer, String> populateAllPositions() {
        Map<Integer, String> allCategories = new TreeMap<Integer, String>();
        allCategories.put(1, "图片新闻");
        allCategories.put(2, "置顶新闻");
        allCategories.put(3, "普通显示");
        return allCategories;
    }

    @ModelAttribute("industryServiceInformation")
    public IndustryServiceInformation populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new IndustryServiceInformation();
        }
        return industryServiceService.getInformationById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{industryServiceInformationId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long industryServiceInformationId, Model model) {
        IndustryServiceInformation industryServiceInformation = industryServiceService.getInformationById(industryServiceInformationId);
        model.addAttribute(industryServiceInformation);
        return "management/industryservice/industryServiceInformationForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new IndustryServiceInformation());
        return "management/industryservice/industryServiceInformationForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid IndustryServiceInformation industryServiceInformation, BindingResult result,
                       @RequestParam("attachments") MultipartFile[] attachments,
                       @RequestParam("delAttachmentIds") Long[] delAttachmentIds, HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/industryservice/industryServiceInformationForm";
        }
        industryServiceService.clearThenSaveOrUpdateInformation(industryServiceInformation);

        if (delAttachmentIds != null) {
            deleteAttachments(industryServiceInformation, delAttachmentIds, request.getSession().getServletContext());
        }

        if (attachments.length > 0) {
            processAttachments(industryServiceInformation, attachments, request.getSession().getServletContext());
        }
        industryServiceService.saveOrUpdateInformation(industryServiceInformation);

        return "redirect:/management/industryservice/informations/search";
    }

    private void deleteAttachments(IndustryServiceInformation industryServiceInformation, Long[] delAttachmentIds, ServletContext servletContext) {
        List<IndustryServiceInformationAttachment> attachmentList = industryServiceInformation.getAttachmentList();
        if (attachmentList == null) {
            return;
        }
        String industryServiceInformationPath = servletContext.getRealPath("/upload/industryServiceInformation/" + industryServiceInformation.getId());
        File industryServiceInformationDir = new File(industryServiceInformationPath);
        if (!industryServiceInformationDir.exists()) industryServiceInformationDir.mkdirs();

        for (Iterator<IndustryServiceInformationAttachment> iterator = attachmentList.iterator(); iterator.hasNext();) {
            IndustryServiceInformationAttachment attachment = iterator.next();
            for (Long delAttachmentId : delAttachmentIds) {
                if (attachment.getId().equals(delAttachmentId)) {
                    iterator.remove();
                    attachmentList.remove(attachment);
                    attachment.setInformation(null);
                    File toDelFile = new File(industryServiceInformationDir, attachment.getName());
                    if (toDelFile.exists()) toDelFile.delete();
                }
            }
        }
    }

    private void processAttachments(IndustryServiceInformation industryServiceInformation, MultipartFile[] attachments, ServletContext servletContext) throws IOException {

        String industryServiceInformationPath = servletContext.getRealPath("/upload/industryServiceInformation/" + industryServiceInformation.getId());
        File industryServiceInformationDir = new File(industryServiceInformationPath);
        if (!industryServiceInformationDir.exists()) industryServiceInformationDir.mkdirs();

        List<IndustryServiceInformationAttachment> attachmentList = industryServiceInformation.getAttachmentList();
        if (attachmentList == null) {
            attachmentList = new ArrayList<IndustryServiceInformationAttachment>();
            industryServiceInformation.setAttachmentList(attachmentList);
        }
        for (MultipartFile attachment : attachments) {
            if (attachment == null || attachment.isEmpty()) {
                continue;
            }
            String originalFilename = attachment.getOriginalFilename();
            File target = new File(industryServiceInformationDir, attachment.getOriginalFilename());
            if (target.exists()) {
                target.delete();
            } else {
                attachmentList.add(new IndustryServiceInformationAttachment(originalFilename, industryServiceInformation));
            }

            FileHelper.saveFile(attachment.getInputStream(), target);
        }
    }    
}
